# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://rui.hzzmdz.com/pay/payment'
_QUERY_GATEWAY = 'http://apitest.hzzmdz.com/pay/payquery'

APP_CONF = {
    '57752125': {  # loki 智能云 支付宝3%（1---5W）D0结算
        'API_KEY': 'd334cb030f2935c306ed47454a8c18dd',
        'gateway': 'http://api.068063.cn/pay/action',
        'query_gateway': 'http://api.068063.cn/pay/select',
    },
    '1044': {  # loki 智能云 支付宝3%（1---5W）D0结算
        'API_KEY': '280263a5a6ee0d8647350da1da699f61',
        'gateway': 'http://api.068063.cn/pay/action',
        'query_gateway': 'http://api.068063.cn/pay/select',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


# goodsname + istype + notify_url + orderid + orderuid + price + return_url + token + uid
def generate_sign(d, key):
    s = d['goodsname'] + d['istype'] + d['notify_url'] + d['orderid'] + d['orderuid'] + d['price'] + d[
        'return_url'] + key + d['uid']
    _LOGGER.info("zhinengyunpay sign str: %s", s)
    return _gen_sign(s)


# orderid + orderuid + ordno + price + realprice + token
def generate_notify_sign(d, key):
    s = d['orderid'] + d['orderuid'] + d['ordno'] + d['price'] + d['realprice'] + key
    _LOGGER.info("zhinengyunpay notify sign str: %s", s)
    return _gen_sign(s)


# uid + orderid + price + orderuid + token
def generate_query_sign(d, key):
    s = d['uid'] + d['orderid'] + d['price'] + d['orderuid'] + key
    _LOGGER.info("zhinengyunpay query sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['key']
    params.pop('key')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("zhinengyunpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 付款方式编号
# 10001 支付宝 20001 微信
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '20001'
    elif service == 'alipay':
        payType = '10001'
    else:
        payType = '10001'
    return payType


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('uid', app_id),
        ('orderid', str(pay.id)),
        ('istype', _get_pay_type(service)),
        ('price', str(int(pay_amount))),
        ('goodsname', 'charge'),
        ('orderuid', 'charge'),
        ('notify_url', '{}/pay/api/{}/zhinengyunpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('return_url',
         '{}/pay/api/{}/zhinengyunpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('format', 'web'),
    ))
    parameter_dict['key'] = generate_sign(parameter_dict, api_key)
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    url = settings.PAY_CACHE_URL + cache_id
    _LOGGER.info("zhinengyunpay create: %s, url: %s", parameter_dict, url)
    return {'charge_info': url}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("zhinengyunpay notify body: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("zhinengyunpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['orderid']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('zhinengyunpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = 'success'
    trade_no = data['ordno']
    total_fee = float(data['realprice'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'success':
        _LOGGER.info('zhinengyunpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('uid', app_id),
        ('orderid', str(pay_order.id)),
        ('price', str(int(pay_order.total_fee))),
        ('orderuid', 'charge'),
    ))
    parameter_dict['key'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info('zhinengyunpay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info('zhinengyunpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['status'])
        total_fee = float(data['realprice'])
        trade_no = data['ordno']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 状态信息，1 支付成功，回调成功 2 支付成功，通知 中 3 待支付 4 订单超时，已关闭
        if trade_status in ['1', '2']:
            _LOGGER.info('zhinengyunpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
